import TipsManager from "../../UIFrame/TipsManager";
import AdMGBackend from "../AdMGBackend";
import AdsIdConfig from "../AdsIdConfig";
import { PlatformAdApi } from "../PlatformAdApi";

const { ccclass, property } = cc._decorator;

@ccclass
export default class WXADApi implements PlatformAdApi {

    videoType: string;
    arg: any;

    /**平台环境 */
    wx: any = window["wx"];
    /**banner */
    bannerAd: any = null;
    /**标记是否为自动关闭banner广告 */
    _autoBannerClose: boolean = false;
    /**插屏 */
    interstitialAd: any = null;
    /**视频 */
    rewardedVideoAd: any = null;
    /**视频广告是否已经load到数据 */
    m_videoAdIsLoaded: boolean = false;
    /**原生 */
    nativeAd: any = null;
    /**原生load取值 */
    resTemp: any = null;
    /**盒子广告 */
    gridAd: any = null;

    title: string = '超上瘾的解密游戏，挑战你的智商！';
    /**分享图地址 */
    shareUrl: string = "https://res.efunent.com/dev2/web2/LceFirePeople/qq/data/share.jpg'";

    /**系统信息 */
    systemInfo: any = null;

    onInit(_callback: Function) {

        if (this.wx !== null && this.wx !== undefined) {
            this.systemInfo = this.wx.getSystemInfoSync();

            this.createVideo();
        } else {
            this.wx = null;
        }

        _callback && _callback();
        console.log('wx ===================> onInit   ok');
    }
    onLogin() {

    }
    onShare(_callback: Function) {
        if (this.wx != null && this.wx != undefined) {
            console.log("wx平台 分享");
            this.wx.shareAppMessage({
                title: this.title,
                imageUrl: this.shareUrl,
                success: () => {
                    _callback && _callback(1);
                },
                fail: () => {
                    _callback && _callback(0);
                }
            });
        }
    }
    onShareVideo(_callback: Function) {

    }
    createBanner() {

    }
    showBanner(adIdKey: string, openIdKey: string) {
        if (this.wx !== null && this.wx !== undefined) {
            this.hideBanner(true);
            this._autoBannerClose = false;
            console.log("wx平台 创建横幅广告");
            this.bannerAd = this.wx.createBannerAd({
                adUnitId: AdsIdConfig.wxId[adIdKey],
                style: {
                    left: 0,
                    top: this.systemInfo.windowHeight - 300 / 2.88,
                    width: 320
                }
            });
            this.bannerAd.onError(err => {
                console.log(err)
            })

            this.bannerAd.onResize((size) => {
                this.bannerAd.style.top = this.systemInfo.windowHeight - size.height;
                this.bannerAd.style.left = (this.systemInfo.windowWidth - size.width) / 2;
            });

            this.bannerAd.onLoad(() => {
                console.log("横幅广告调用 onLoad");

                this.bannerAd.show().catch(err => console.log('wx banner show失败==》', JSON.stringify(err)));
            });
        }
    }
    hideBanner(close = false) {
        if (this.bannerAd) {
            console.log("wx平台 销毁横幅广告");
            if (!close) {
                this._autoBannerClose = true;
            }
            this.bannerAd.hide();
            this.bannerAd.destroy();
            this.bannerAd = null;
        }
    }
    createVideo() {
        if (this.wx !== null && this.wx !== undefined) {
            if (this.rewardedVideoAd) {
                this.rewardedVideoAd.destroy();
                this.rewardedVideoAd = null;
            }
            /**创建rewardedVideoAd 对象*/
            console.log("wx平台 创建激励视频广告");
            this.rewardedVideoAd = this.wx.createRewardedVideoAd({
                adUnitId: AdsIdConfig.wxId['video'],
            });
            this.rewardedVideoAd.load();
            this.rewardedVideoAd.onLoad(() => {
                console.log("激励视频广告 加载成功");
                this.m_videoAdIsLoaded = true;
            });
            this.rewardedVideoAd.onError((err) => {
                console.log('wxH5GameAPI 激励视频 加载失败:code =====>:' + err.code + "message ======>:" + JSON.stringify(err));
                this.m_videoAdIsLoaded = false;
            });
        }
    }
    showVideo(_type: string, _successCallback?: Function, _failCallback?: Function) {
        this.videoType = _type;
        /**确保video正常创建并已经拉取到数据 */
        if (this.rewardedVideoAd && this.m_videoAdIsLoaded) {
            this.rewardedVideoAd.show();
            const onClose = (res) => {
                if (res.isEnded) {
                    console.log('激励视频广告完成，发放奖励');
                    /**播放完毕 处理播放成功的逻辑 */
                    _successCallback && _successCallback();
                    this.rewardedVideoAd.load();
                } else {
                    console.log('激励视频广告取消关闭，不发放奖励');
                    /**播放失败 处理播放失败的逻辑 */
                    _failCallback && _failCallback();
                    this.rewardedVideoAd.load();
                }
                this.rewardedVideoAd.offClose(onClose);
            }
            this.rewardedVideoAd.onClose(onClose);
        } else {
            /**没有成功创建广告或者没有成功load广告 就重新创建一个 */
            TipsManager.Instance().create("广告还未准备好,请稍后再试");
            _failCallback && _failCallback();
            this.createVideo();
        }
    }
    showVideoAward() {

    }
    showVideoFail() {

    }
    createInsertAd() {

    }
    showInsertAd(adIdKey: string, openIdKey?: string) {
        if (this.wx != null && this.wx != undefined) {
            if (this.interstitialAd) {
                this.interstitialAd.destroy();
                this.interstitialAd = null;
            }
            this.interstitialAd = this.wx.createInterstitialAd({
                adUnitId: AdsIdConfig.wxId[adIdKey],
            });
            this.interstitialAd.onLoad(() => {
                this.interstitialAd.show();
            });
            this.interstitialAd.onError((res) => {
                console.log('wx InsertAd load Error:' + JSON.stringify(res));
                this.interstitialAd.destroy();
                this.interstitialAd = null;
            });
            const onClose = (res) => {
                console.log("用户关闭插屏广告并销毁");
                AdMGBackend.getInstance().adClose(openIdKey);
                this.interstitialAd.offClose(onClose);
                this.interstitialAd.destroy();
                this.interstitialAd = null;
            };
            this.interstitialAd.onClose(onClose);
            this.interstitialAd.load();
        }
    }
    createNativeAd() {

    }
    showNativeAd(adIdKey: string, _callback: Function, openIdKey?: string) {
    }
    onNativeAdClick(_id: string) {
    }
    onNativeReportAdShow(_id: string){
    }
    createNativeIconAd() {

    }
    showNativeIconAd() {

    }
    onNativeIconAdClick(_id: string) {

    }
    createGridAd(adIdKey: string, openIdKey?: string) {
        if (this.wx != null && this.wx != undefined) {
            if (this.gridAd) {
                this.gridAd.destroy();
                this.gridAd = null;
            }
            this.gridAd = this.wx.createGridAd({
                adUnitId: AdsIdConfig.wxId[adIdKey],
                style: {},
                adTheme: 'white',
                gridCount: 8
            });
            this.gridAd.load();
            this.gridAd.onLoad(() => {
                this.gridAd.show();
            });
            this.gridAd.onError((res) => {
                console.log('wx InsertAd load Error:' + JSON.stringify(res));
                this.gridAd.destroy();
                this.gridAd = null;
            });
            const onClose = (res) => {
                console.log("用户关闭插屏广告并销毁");
                AdMGBackend.getInstance().adClose(openIdKey);
                this.gridAd.offClose(onClose);
                this.gridAd.destroy();
                this.gridAd = null;
            };
            this.gridAd.onClose(onClose);
        }
    }
    saveDataToCache(_key: string, _value: any) {

    }
    readDataFromCache(_key: string) {

    }
    addDesktop(_callback: Function) {
    }
    /**是否已经创建桌面图标 */
    hasShortcutInstalled(_callback: Function) {
    }
    startRecordScreen() {

    }
    stopRecordScreen() {

    }
    createMoreGamesBtn() {

    }
    showMoreGamesBtn() {

    }
    jumpToGame(_packageName: string) {

    }
    addColorBookmark() {

    }
    addSubscribeApp() {

    }

    vibrateShort() {
        this.wx.vibrateShort && this.wx.vibrateShort();
    }

    vibrateLong() {
        this.wx.vibrateLong && this.wx.vibrateLong();
    }

}
